import axios from 'axios'
import { Message } from 'element-ui';
import qs from 'qs'

export const error = async msg => {
  await Message({
    type: 'error',
    message: msg,
    showClose: true
  })
}

export const warning = async msg => {
  await Message({
    type: 'warning',
    message: msg,
    showClose: true
  })
}

/**
 * 设置axios请求属性
 * @type {number}
 */
axios.defaults.timeout = 5000 //请求超时5秒
// axios.defaults.baseURL = '/wsvtp'  //请求base url
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' //设置post请求是的header信息

/**
 * 请求头Token
 */
axios.interceptors.request.use(
  config => {
    let accessToken = localStorage.getItem('accessToken')
    if (accessToken) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers = {
        accessToken,
        // 'content-type': 'application/json',
      }
    }
    return config
  },
  err => {
    return Promise.reject(err)
  },
)

/**
 * 设置返回头
 */
axios.interceptors.response.use(
  response => {
    // if (response.data.code !== 1) {
    //   error(response.data.msg)
    // }
    console.log("httpBack",response)
    return response.data
  },
  // 请求失败
  err => {
    console.log('requestErr', err)
    warning('网络异常，连接超时...')
    return Promise.reject(err)
  },
)

/**
 * 封装get请求
 * @param url
 * @param data 请求参数
 * @returns {Promise}
 */
export function get (url, params = {}, headers = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params,
      headers: headers,
    }).then(response => {
      console.log("response",response)
      // if(response.code !== 1) {
      //   reject(response.msg)
      // }
      resolve(response.results)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post (url, data = {}, params = {}, headers = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data, {
      params: params,
      headers: headers,
    }).then(response => {
      console.log("response",response)
      // if(response.code !== 1) {
      //   reject(response.msg)
      // }
      resolve(response.results)
    }).catch(err => {
      reject(err)
    })
  })
}
